﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Store.Models;
using Store.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Store.Controllers
{

    [Route("/[action].html")]
    [Route("/Register.html")]
    [Route("/Login.html")]
    [Route("/UserInfo.html")]

    public class HomeController : Controller
    {

        private readonly Store_2022Context _db;
        public HomeController(Store_2022Context db)
        {
            _db = db;
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Market(int cateId)
        {
            var cates = _db.Categories.ToList();           
            ViewData["Cates"] = cates;
            if (cateId == 0)
            {
                cateId = cates.FirstOrDefault().Id;
            }
            var goods = _db.Goods.Where(x => x.CateId == cateId).ToList();           
            ViewData["Goods"] = goods;
            ViewData["CateId"] = cateId;

            return View();
        }

        public IActionResult Detail(int id)
        {
            var good = _db.Goods.FirstOrDefault(x => x.Id == id);          
            ViewData["Good"] = good;
            return View();
        }

        public IActionResult About()
        {
            return View();
        }

        [Authorize]
        public IActionResult Userinfo()
        {
            var userId = Convert.ToInt32(HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
            //在数据库查询用户数据
            var user = _db.Users.FirstOrDefault(x => x.UserId == userId);
            ViewData["User"] = user;
            return View();

        }
        public IActionResult Register()
        {
            return View();
        }
        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public IActionResult RegisterAccount(RegisterAccountRequest request)
        {
            //判断用户名是否存在
            var result = _db.Users.Any(x => x.UserName == request.UserName);
            if (result)
                return Content("账号已存在");

            //添加数据
            var data = new User
            {
                CraeteTime = DateTime.Now,
                Password = request.Password,
                Photo = String.Empty,
                UserName = request.UserName
            };
            _db.Users.Add(data);
            var row = _db.SaveChanges();
            if (row > 0)
                return Content("注册成功");
            return Content("注册失败");
        }
        [HttpPost]
        public IActionResult LoginAccount(LoginAccountRequest request)
        {
            //数据库查询账号密码是否存在
            var user = _db.Users.FirstOrDefault(x => x.UserName == request.UserName);
            if (user == null)
                return Content("用户不存在");
            if (user.Password != request.Password)
                return Content("密码错误");

            return Content("登录成功");
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier,user.UserId.ToString()),
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Thumbprint, user.Photo),
            };
            HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
            return Content("登录成功");
        }

        [HttpGet]
        public IActionResult LoginOut()
        {
            HttpContext.SignOutAsync();
            return RedirectToAction("Index");
        }

        [Authorize]
        public IActionResult AddCar(AddCarRequest request)
        {
            var data = HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;

            //获取授权中的用户Id
            var uId = Convert.ToInt32(data);
            //2、加入购物车需求
            //  如果购物车有这个商品记录 购物车的记录 数量+1 


            //                                条件   商品Id=前端商品Id并且 用户Id==登录用户Id                    
            var record = _db.Cars.FirstOrDefault(x => x.GoodId == request.GoodId && x.Uid == uId);
            if (record != null)//存在
            {
                //自增1
                record.Count += 1;
                _db.Cars.Update(record);
            }
            else
            {
                //  否则在购物车表创建一个条记录
                record = new Car
                {
                    GoodId = request.GoodId,
                    Uid = uId,
                    CreateTime = DateTime.Now,
                    Count = 1
                };
                _db.Cars.Add(record);
            }
            var row = _db.SaveChanges();
            if (row > 0)
                return Content("加入成功");
            return Content("加入失败");
        }
    }

}


